package zhieasy.cn.xpu_helper.controller.book_market;

import com.github.zouchanglin.storage.service.upload.result.ReturnBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import zhieasy.cn.common.utils.ResultVOUtil;
import zhieasy.cn.common.utils.result.ResultUtils;
import zhieasy.cn.common.vo.ResultVO;
import zhieasy.cn.model.book_market.UserBook;
import zhieasy.cn.service.book_market.BookService;

import javax.servlet.ServletContext;
import java.util.HashMap;

/**
 * @author DaHang
 * @date 2020/8/1 9:26
 * 用来处理失物招领上传对象存储的类
 */
@RequestMapping("/book-market/object")
@RestController
@ApiIgnore
public class UploadController {

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private BookService bookService;

    /**
     * 图片上传回调方法
     * @param parentId 帖子id
     * @param returnBody 回调传来的详细信息
     * @return 无所谓
     */
    @RequestMapping(value = "/callback/{parentId}",method = RequestMethod.POST)
    public ResultVO objectCallBack(@PathVariable("parentId") String parentId,
                                   @RequestBody ReturnBody returnBody){
        if (1==1){
            return ResultUtils.success();
        }
        //获取一下这个List
        HashMap<String,String> imageMap = (HashMap<String, String>) servletContext.getAttribute(parentId);
        //获取一下上传的object的key
        String name = returnBody.getFname();
        //看看有没有这个文件
        String s = imageMap.get(name);
        if (s == null)
            //没有这个元素出错了
            return ResultUtils.success();
        //从map里面取出来，设置成url路径放回去
        imageMap.remove(name);
        imageMap.put(name,returnBody.getBucket());
        //看一下成功没
        boolean flag = true;
        for (String url: imageMap.values()) {
            if (url == ""){
                flag = false;
            }
        }
        //如果为true那就是全部都上传成功了，那就可以上传了
        if (flag){
            //TODO 上传成功
            UserBook userBook = (UserBook) servletContext.getAttribute(parentId + "ob");
            String imageUrls = "";
            for (String url : imageMap.values()) {
                imageUrls += "\"" + url + "\"" + ",";
            }
            //把逗号去掉
            imageUrls = imageUrls.substring(0, imageUrls.length() - 1);
            userBook.setImageUrls(imageUrls);
            //这里需要处理一下图片的存储路径
            bookService.putBook(userBook);
            servletContext.removeAttribute(userBook.getUbId()+"flag");
            servletContext.setAttribute(userBook.getUbId()+"flag",true);
        }
        //如果为空，那么就是图片都已经上传成功了,这里调用service去将数据保存在db中
        return ResultVOUtil.success();
    }
}
